package algorithm.leetcode.medium;

/*
 给定一个非空字符串 s 和一个包含非空单词的列表 wordDict，
 判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
 */

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/12/3
 */
public class Question139 {

    public static void main(String[] args) {
        String s = "applepenapple";
        List<String> wordDict = Arrays.asList("apple", "pen");
        Question139 question = new Question139();
        boolean flg = question.wordBreak(s, wordDict);
        System.out.println(flg);
    }

    private Map<String, Boolean> map = new HashMap<>(8);

    /**
     * 思路： 转移方程：dp[j] = dp[i] && check(s[i+1, j]);
     */
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length() + 1];

        for (String word : wordDict) {
            map.put(word, true);
        }

        dp[0] = true;

        for (int i = 1; i <= s.length(); i++) {
            for (int j = i - 1; j >= 0; j--) {
                dp[i] = dp[j] && check(s.substring(j, i));
                if (dp[i]) {
                    break;
                }
            }
        }
        return dp[s.length()];
    }

    private boolean check(String substring) {
        return map.getOrDefault(substring, false);
    }

}
